import { Component, createRef, type Key } from "react";
import {
  Table,
  Tag,
  type TableColumnsType,
  Button,
  Space,
  message,
} from "antd";
import { connect, ConnectedProps } from "react-redux";
import { TableRowSelection } from "antd/es/table/interface";

import { person } from "@/store/modules/user";
import { addMenu, deleteMenu, getMenuPage, updateMenu } from "@/api/menu";
import { deepTree } from "@/utils";

import UpsertModal from "./components/upsert-modal";

interface IState {
  list: Menu.Item[];
  checkedIds: Key[];
}

class Menu extends Component<PropsFromRedux, IState> {
  upRef = createRef<UpsertModal>();

  // 初始化 state
  state: Readonly<IState> = {
    list: [],
    checkedIds: [],
  };

  columns: TableColumnsType<Menu.Item> = [
    { title: "Id", dataIndex: "id" },
    { title: "菜单名称", dataIndex: "name" },
    {
      title: "菜单类型",
      dataIndex: "type",
      render: (_, { type }) => {
        switch (type) {
          case 0:
            return <Tag color="green">目录</Tag>;
          case 1:
            return <Tag color="red">菜单</Tag>;
          case 2:
            return <Tag color="yellow">按钮</Tag>;
          default:
            return <Tag color="green">不详</Tag>;
        }
      },
    },
    { title: "路由地址", dataIndex: "router" },
    { title: "组件地址", dataIndex: "viewPath" },
    {
      title: "操作",
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            onClick={() => this.upRef.current?.open(record)}
          >
            编辑
          </Button>
          <Button
            type="primary"
            size="small"
            danger
            onClick={() => this.handleDel([record.id])}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  /**
   * 勾选框勾选时触发
   */
  changeSelection: TableRowSelection<Menu.Item>["onChange"] = (checkedIds) => {
    this.setState({
      checkedIds: checkedIds,
    });
  };

  /**
   * 刷新数据
   */
  refresh = () => {
    getMenuPage({ size: 1000 }).then((resp) => {
      const tree = deepTree(resp.list);
      this.setState({
        list: tree,
      });
    });
  };

  /**
   * UpsertModal 内部触发，用于处理 新增与编辑
   */
  upOk = async (params: any) => {
    console.log("upOk", params);
    // 根据 params 中是否有 id 来调用不同的接口
    if (params.id) {
      await updateMenu(params);
      message.success("编辑成功");
    } else {
      await addMenu(params);
      message.success("新增成功");
    }
    // 刷新数据
    this.refresh();
    // 关闭弹窗
    this.upRef.current?.close();
    // 触发 个人信息的动作 让左侧数据重新渲染
    this.props.handlePerson();
  };

  /**
   * 删除
   */
  handleDel = async (ids: Key[]) => {
    await deleteMenu({
      ids,
    });
    message.success("删除成功");
    // 刷新数据
    this.refresh();
    // 触发 个人信息的动作 让左侧数据重新渲染
    this.props.handlePerson();
  };

  render() {
    const { checkedIds } = this.state;

    return (
      <Space direction="vertical" style={{ display: "flex" }}>
        <h2>菜单列表</h2>

        <Space>
          <Button type="primary" onClick={() => this.upRef.current?.open()}>
            新增
          </Button>

          <Button
            danger
            disabled={!checkedIds.length}
            onClick={() => this.handleDel(checkedIds)}
          >
            删除
          </Button>
        </Space>

        <Table
          bordered
          size="small"
          rowKey="id"
          columns={this.columns}
          dataSource={this.state.list}
          rowSelection={{
            onChange: this.changeSelection,
          }}
        />

        {/* 新增or编辑的弹窗 */}
        <UpsertModal ref={this.upRef} onOk={this.upOk} />
      </Space>
    );
  }

  componentDidMount() {
    this.refresh();
  }
}

const connector = connect(null, {
  handlePerson: person,
});

type PropsFromRedux = ConnectedProps<typeof connector>;

export default connector(Menu);
